import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import Login from '@/views/Login.vue';
import Dashboard from '@/views/Dashboard.vue';
import Users from '@/views/Users.vue';
import Orders from '@/views/Orders.vue';
import Products from '@/views/Products.vue';
import Profile from '@/components/Profile.vue';
import ChangeAvatar from '@/components/ChangeAvatar.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', name: 'login', component: Login },
  { path: '/dashboard', name: 'dashboard', component: Dashboard, meta: { requiresAuth: true } },
  { path: '/users', name: 'users', component: Users, meta: { requiresAuth: true, role: 'admin' } },
  { path: '/orders', name: 'orders', component: Orders, meta: { requiresAuth: true } },
  { path: '/products', name: 'products', component: Products, meta: { requiresAuth: true } },
  { path: '/profile', name: 'profile', component: Profile, meta: { requiresAuth: true } },
  { path: '/change-avatar', name: 'change-avatar', component: ChangeAvatar, meta: { requiresAuth: true } },
];

const router = new VueRouter({
  mode: 'history',
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.state.isAuthenticated) {
      next({ name: 'login' });
    } else if (to.meta.role && store.state.role !== to.meta.role) {
      next({ name: 'dashboard' });
    } else {
      next();
    }
  } else {
    next();
  }
});

// 修改导航方法，处理 NavigationDuplicated 错误
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err;
  });
};

export default router;
